package edu.zju.gis.dbfg.common.util;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 * @author Hu
 * @date 2019/4/27
 **/

public final class HttpUtil {

  /**
   * 获取Post请求的请求体
   * @param request
   * @return
   */
  public static String getRequestBody(HttpServletRequest request) {
    StringBuilder sb = new StringBuilder();
    InputStream inputStream = null;
    BufferedReader reader = null;
    try {
      inputStream = request.getInputStream();
      reader = new BufferedReader(
        new InputStreamReader(inputStream, Charset.forName("UTF-8")));

      char[] bodyCharBuffer = new char[1024];
      int len = 0;
      while ((len = reader.read(bodyCharBuffer)) != -1) {
        sb.append(new String(bodyCharBuffer, 0, len));
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (inputStream != null) {
        try {
          inputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return sb.toString();
  }


  /**
   * 获取客户端ip地址
   * @param request
   * @return
   */
  public static String getCliectIp(HttpServletRequest request) {
    String ip = request.getHeader("x-forwarded-for");
    if (ip == null || ip.trim() == "" || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("Proxy-Client-IP");
    }
    if (ip == null || ip.trim() == "" || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if (ip == null || ip.trim() == "" || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getRemoteAddr();
    }

    // 多个路由时，取第一个非unknown的ip
    final String[] arr = ip.split(",");
    for (final String str : arr) {
      if (!"unknown".equalsIgnoreCase(str)) {
        ip = str;
        break;
      }
    }
    return ip;
  }

  /**
   * 判断是否为ajax请求
   * @param request
   * @return
   */
  public static String getRequestType(HttpServletRequest request) {
    return request.getHeader("X-Requested-With");
  }



}